//
// Created by 莫吉米 on 16/8/9.
//
#include <mysql.h>
#include <string>
#include <iostream>

using namespace std;

#include "Connector.h"

Connector::Connector():queryres(NULL)
{
    mysql_init(&mysql);
}
Connector::~Connector()
{
    mysql_close(&mysql);
}

void Connector::Connect(string host, string user, string passwd, string db,unsigned int port, const char *socket,
                        unsigned long flag)
{
    if(!mysql_real_connect(&mysql,host.c_str(),user.c_str(),passwd.c_str(),db.c_str(),port,socket,flag))
    {
        cerr<<"Failed to connect to database"<<endl;
        mysql_error(&mysql);
    }
}
int  Connector::Query(string sql)
{
    if(mysql_real_query(&mysql,sql.c_str(),sql.size()))
    {
        cerr<<"Query Error"<<endl;
        return NULL;
    }
    else
    {
        queryres=mysql_store_result(&mysql);
        if(queryres==NULL)
            return 0;
        else
            return (int)mysql_num_rows(queryres);
    }
}

int Connector::FetchRow() {
    row = mysql_fetch_row(queryres);
    if(row==NULL)
        return 0;
    else
        return (int)*mysql_fetch_lengths(queryres);
}

string Connector::Getstring(int index) {
    if(row[index])
        return string(row[index]);
    else
        return string("");
}

int Connector::Getint(int index) {
    if(row[index])
        return atoi(row[index]);
    else
        return 0;
}

void Connector::Update(string sql)
{
    if(mysql_real_query(&mysql,sql.c_str(),sql.size()))
    {
        cerr<<"Query Error"<<endl;
    }
}







